package com.mgface.framework.concurrent;

import java.util.concurrent.atomic.AtomicReference;
/**
 * Treiber算法的非阻塞堆栈
 * @author yuxiang
 *
 * @param <E>
 */
public class ConcurrentStack<E> {
	private AtomicReference<Node<E>> head = new AtomicReference<>();
    
	public void push(E item){
		Node<E> newHead = new Node<E>(item);
		Node<E> old;
		do{
			old = head.get();
			newHead.next = old;
		}while(!head.compareAndSet(old, newHead));
	}
	
	public E pop(){
		Node<E> oldHead;
		Node<E> newHead;
		do{
			oldHead = head.get();
			if(oldHead==null){
				return null;
			}
			newHead = oldHead.next;
		}while(!head.compareAndSet(oldHead, newHead));
		return oldHead.item;
	}
	
	static class Node<E> {
       final E item;
       Node<E> next;
       public Node(E item){
    	   this.item = item;
       }
	}
}
